package com.allen.control;

import com.allen.bean.Goods;
import com.allen.service.ChartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/chartCtrl")
public class ChartControl extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String parm = req.getParameter("parm");
        switch (parm) {
            case "list":
                list(req, resp);
                break;
            case "chart":
                chart(req, resp);
        }
    }

    private void chart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int gid = Integer.parseInt(req.getParameter("gid"));
        String chartsJson = new ChartService().chartJson(gid);
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(chartsJson);
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Goods> goodses = new ChartService().getAllGoods();
        req.setAttribute("goodses", goodses);
        req.getRequestDispatcher("/chart/list.jsp").forward(req, resp);
    }
}
